package pl.edu.agh.pros.renewal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PeriodicalExecutor {

	private Thread executionThread;
	private List<ExecutionTask> tasks = Collections.synchronizedList(new ArrayList<ExecutionTask>());
	private final Long executionInterval;

	PeriodicalExecutor(Long executionInterval) {
		this.executionInterval = executionInterval;
	}

	public void addTask(ExecutionTask task, int position) {
		synchronized (tasks) {
			tasks.add(position, task);
			if (executionThread == null || !executionThread.isAlive()) {
				start();
			}
		}
	}

	public void removeTask(ExecutionTask task) {
		synchronized (tasks) {
			tasks.remove(task);
			if (tasks.isEmpty()) {
				executionThread.interrupt();
			}
		}
	}

	public void stop() {
		executionThread.interrupt();
	}

	void start() {
		executionThread = new Thread() {
			@Override
			public void run() {
				while (!executionThread.isInterrupted()) {
					try {
						Thread.sleep(executionInterval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (tasks) {
						for (ExecutionTask task : tasks) {
							try {
								task.execute();
							} catch (Exception e) {
								// ignore
							}
						}
					}
				}
			}
		};
		executionThread.setDaemon(true);
		executionThread.start();
	}

}
